<?php
namespace App\Components;
use Cache;
use Carbon\Carbon;
use App\Components\Tools;
/**
 * 抖音工具类
 */
class DyTools {
	protected $client_key = '';
	protected $client_secret = '';
	protected $redirect_uri = '';
	
	/**
	*	读取配置 type 0 全部内容     非空读取该字段值
	*	$client_key  $client_secret  $redirect_uri
	*/
	function third($type){
		$douyinData=Tools::getThird('/config/third.json');
		$data=array(
			'client_key'=>isset($douyinData['douyin']['dy_client_key']) ? $douyinData['douyin']['dy_client_key'] : '',
			'client_secret'=>isset($douyinData['douyin']['dy_client_secret']) ? $douyinData['douyin']['dy_client_secret'] : '',
			'redirect_uri'=>isset($douyinData['douyin']['redirect_uri']) ? $douyinData['douyin']['redirect_uri'] : '',
		);
		$this->client_key=$data['client_key'];
		$this->client_secret=$data['client_secret'];
		$this->redirect_uri=$data['redirect_uri'];
		
		// echo $this->redirect_uri;exit;
		if($type){
			return $data[$type];
		}
		return $data;
	}
	
  function renewRefreshToken($refresh_token){
    $url = "https://open.douyin.com/oauth/renew_refresh_token/?client_key=".self::$client_key."&refresh_token=".$refresh_token;
    $res = $this->getJson($url);
    $data = isset($res['data']) ? $res['data'] : [];
    Tools::commandsLog('renewRefreshToken='.json_encode($data));
    return $data;
  }

  function refreshToken($refresh_token){
    $url = "https://open.douyin.com/oauth/refresh_token/?client_key=".self::$client_key."&grant_type=refresh_token&refresh_token=".$refresh_token;
    $res = $this->getJson($url);
    $data = isset($res['data']) ? $res['data'] : [];
    Tools::commandsLog('refreshToken='.json_encode($data));
    return $data;
  }

  /**
   * 关键词视频搜索
   */
  function videoSearch($open_id,$access_token,$cursor,$keyword,$count){
    $url = "https://open.douyin.com/video/search/?open_id={$open_id}&access_token={$access_token}&cursor={$cursor}&keyword={$keyword}&count={$count}";
    $client = new \GuzzleHttp\Client();
    $response = $client->request('GET',$url);
    $data = $this->loadResult($response);
    Tools::commandsLog('videoSearch='.json_encode($data));
    return $data;
  }
  
  function clientToken($refresh = false){
    $result = Cache::get('dy_client_access_token');
    if(!empty($result)){
      if($refresh){
        Cache::forget('dy_client_access_token');
        $this->clientToken();
      }
      $result = unserialize($result);
    }else{
      $url = 'https://open.douyin.com/oauth/client_token/?grant_type=client_credential&client_key='.self::$client_key.'&client_secret='.self::$client_secret;
      $res = $this->getJson($url);
      Tools::commandsLog('clientToken='.json_encode($res));
      $result = (isset($res['data']['access_token']) ? $res['data']['access_token'] : FALSE);
      $expiresAt = Carbon::now()->addHours(1)->addMinutes(50);//缓存1小时50分钟    6600s
      Cache::put('dy_client_access_token',serialize($result),$expiresAt);
    }
    return $result;
  }


  /**
   * 关键词视频评论列表
   */
  function videoSearchComment($cursor,$sec_item_id,$count){
    $url = "https://open.douyin.com/video/search/comment/list/?access_token=".self::clientToken()."&cursor={$cursor}&sec_item_id={$sec_item_id}&count={$count}";
    $client = new \GuzzleHttp\Client();
    $response = $client->request('GET',$url);
    $data = $this->loadResult($response);
    Tools::commandsLog('videoSearchComment='.json_encode($data));
    return $data;
  }

  function userinfo($open_id,$assess_token){
    $url = "https://open.douyin.com/oauth/userinfo/?access_token={$assess_token}&open_id={$open_id}";
    $res = $this->getJson($url);
    $data = isset($res['data']) ? $res['data'] : [];
    return $data;
  }

  /**
    * 外部API返回处理
    * @param $response
    * @return mixed
    */
  function loadResult($response){
    $response_code = $response->getStatusCode();
    $result = $response->getBody()->getContents();
    $result = json_decode($result, true);
    if (!isset($result['success']) || $result['success'] != true) {
    }
    return $result['data'];
  }

  function getJson($url){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$url);
	curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	curl_setopt($ch, CURLOPT_HEADER, FALSE);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);//为true，则会跟踪爬取重定向页面，否则，不会跟踪重定向页面
	$output = curl_exec($ch);
	curl_close($ch);
	return json_decode($output, true);
  }
  
  function postJson($url, $data = array()){
    //初始化
    $curl = curl_init();
    //设置抓取的url
    curl_setopt($curl, CURLOPT_URL, $url);
    //设置头文件的信息作为数据流输出
    curl_setopt($curl, CURLOPT_HEADER, 0);
    //设置获取的信息以文件流的形式返回，而不是直接输出。
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    //设置post方式提交
    curl_setopt($curl, CURLOPT_POST, 1);
    //设置post数据
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    //执行命令
    $json = curl_exec($curl);
    //关闭URL请求
    curl_close($curl);
    return json_decode($json, true);
  }
}
